package org.popo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectServer;
import com.db4o.ObjectSet;
import com.db4o.cs.Db4oClientServer;

public class DB4OUtils {
	private static final String DB_FILE_SUFFIX = ".db4o.yap";
	public static final String TRADE_PATH = "taobao_trade";
	public static final String ITEM_PATH = "taobao_item";
	public static final String NEW_TRADE_PATH = "new_trade";
	private static final int PORT = 0;

	private static ObjectServer objectServer;

	private static final ThreadLocal<ObjectContainer> dbThreadLocal = new ThreadLocal<ObjectContainer>();

	public static ObjectContainer getObjectContainer() {
		ObjectContainer oc = dbThreadLocal.get();
		if (oc == null || oc.ext().isClosed()) {
			oc = getObjectServer().openClient();
			dbThreadLocal.set(oc);
		}
		return oc;
	}
	public static ObjectContainer getObjectContainer(String name) {
		ObjectContainer oc = dbThreadLocal.get();
		if (oc == null || oc.ext().isClosed()) {
			oc = getObjectServer(name).openClient();
			dbThreadLocal.set(oc);
		}
		return oc;
	}

	public static void closeDb() {
		ObjectContainer oc = dbThreadLocal.get();
		dbThreadLocal.set(null);
		if (oc != null)
			oc.close();
	}

	public static ObjectServer getObjectServer() {
		return getObjectServer(null);
	}

	public synchronized static ObjectServer getObjectServer(String name) {
		return getObjectServer(name, PORT);
	}

	public static ObjectServer getObjectServer(String name, int port) {
		if (name == null) {
			name = "default";
		}
		if (objectServer == null) {
			objectServer = getObjectServerForFilename(name + DB_FILE_SUFFIX,
					port);
		}
		return objectServer;
	}

	public static void shutdown() {
		if (objectServer != null) {
			objectServer.close();
		}
	}

	public static ObjectServer getObjectServerForFilename(String yapfilename,
			int port) {
		File parentDir = getDbDirectory();
		File dbfile = new File(parentDir, yapfilename);
		ObjectServer objectServer = Db4oClientServer.openServer(
				dbfile.getPath(), port);

		return objectServer;
	}

	private static File getDbDirectory() {
		// will store database in {user.home}/db4o-data directory
		String dbfile = System.getProperty("user.home") + "\\db4o\\data";
		System.out.println(dbfile);
		File f = new File(dbfile);
		if (!f.exists()) {
			f.mkdirs();
		}
		return f;
	}

	public static void main(String[] args) {
		getDbDirectory();
	}
}
